package com.shimao.celnet.payment.quartz;

import com.alibaba.fastjson.JSON;
import com.baiwang.bop.respose.entity.InvoiceQueryResponse;
import com.shimao.celnet.payment.controller.apinotcheck.CallOut_invOpenRetInfoOutController;
import com.shimao.celnet.payment.controller.apinotcheck.CallOut_invPdfOutController;
import com.shimao.celnet.payment.controller.apinotcheck.CallOut_invoiceQueryOutController;
import com.shimao.celnet.payment.form.IAppInterfaceForm;
import com.shimao.celnet.payment.model.PInvoiceBlue;
import com.shimao.celnet.payment.service.IAppInterfaceService;
import com.shimao.celnet.payment.service.IInterfaceLogService;
import com.shimao.celnet.payment.service.PInvoiceBlueService;
import com.shimao.celnet.payment.util.FinalUtil;
import com.shimao.celnet.payment.util.GetJFSystemToken;
import com.shimao.celnet.payment.util.HttpSendPostUtil;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.apache.shiro.util.CollectionUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;



import java.util.List;

/**
 * 每间隔一小时扫描蓝票表，有推送状态为0的蓝票，重新推送
 * Created by loki on 2018/8/15.
 */
public class FailInvoicePushAgain implements Job {
    protected Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private IAppInterfaceService iAppInterfaceService;

    @Autowired
    private PInvoiceBlueService pInvoiceBlueService;

    @Autowired
    private GetJFSystemToken getJFSystemToken;

    @Autowired
    private HttpSendPostUtil httpSendPostUtil;

    @Autowired
    private CallOut_invoiceQueryOutController callOut_invoiceQueryOutController;

    @Autowired
    private CallOut_invOpenRetInfoOutController callOut_invOpenRetInfoOutController;

    @Autowired
    private CallOut_invPdfOutController callOut_invPdfOutController;
    @Autowired
    private IInterfaceLogService iInterfaceLogService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException{
       try {
           logger.info("********************定时推送蓝票任务开始执行***********");
           //获取近一个小时的状态为未推送的蓝票记录
           List<PInvoiceBlue> invoiceList = pInvoiceBlueService.invoiceList();
           logger.info("&&&&size:="+invoiceList.size());
           if(!CollectionUtils.isEmpty(invoiceList))
           {
               String strUrl = null;
               for(PInvoiceBlue pInvoiceBlue : invoiceList) {
                   JSONObject RetJsonObject = new JSONObject();
                   InvoiceQueryResponse responseRet = callOut_invoiceQueryOutController.invoiceBlueQueryOut(pInvoiceBlue);
                   logger.info("@@@1" + responseRet.toString());
                   //返回结果
                   if (FinalUtil.INVOICE_TYPE_CODE_026.equals(pInvoiceBlue.getInvoiceTypeCode())) {
                       strUrl = callOut_invPdfOutController.invPdfOut(pInvoiceBlue);

                   }
                   //如果查询结果查询失败，则直接查询本地的数据去回调。
                   if(responseRet == null){
                       //返回结果
                       RetJsonObject = callOut_invOpenRetInfoOutController.invOpenRetBlueInfoOut( pInvoiceBlue, strUrl);
                       logger.info("@@@2" + RetJsonObject.toString());
                   }else{
                       //返回结果
                       RetJsonObject = callOut_invOpenRetInfoOutController.invOpenRetBlueInfoOut(responseRet, pInvoiceBlue, strUrl);
                       System.out.println("@@@3" + RetJsonObject.toString());
                   }
                   List<IAppInterfaceForm> iAppInterfaceFormsList = getRetUrl("20180117", "160");
                   for (IAppInterfaceForm iAppInterfaceForm : iAppInterfaceFormsList) {
                       logger.info("@@@5" + iAppInterfaceForm.getInterfaceId());
                       //当要通知物业计费系统的时候，需要制定回调的接口应用
                       if ("1005".equals(iAppInterfaceForm.getInterfaceId())) {
                           /**
                            * 物业计费的接口验证规则
                            * 只接受来自物业的费用
                            */
                           String token = getJFSystemToken.getJFSystemNewToken("20180117", iAppInterfaceForm.getInterfaceId());
                           //给物业推送消息 如果业务类型里面包含pty则必定是物业费：pty-101支付业务类型:pty-101：物业缴费；pty-102：物业预缴费；
                           String ret = httpSendPostUtil.sendPost(iAppInterfaceForm.getRequestUrl(), RetJsonObject, token, pInvoiceBlue.getAppKey(), iAppInterfaceForm.getInterfaceId());
                           logger.info(RetJsonObject);
                           logger.info(iAppInterfaceForm.getRequestUrl());
                           logger.info(ret);
                           com.alibaba.fastjson.JSONObject retObj = JSON.parseObject(ret);
                           String code = retObj.getString("errcode");
                           logger.info("定时任务推送返回：" + code);
                           if("0".equals(code))
                           {
                               //保存数据库，更改状态
                               pInvoiceBlue.setIsPush("1");
                               pInvoiceBlueService.update(pInvoiceBlue);

                           }

                       } else {
                           String result = httpSendPostUtil.sendPost1(iAppInterfaceForm.getRequestUrl(), RetJsonObject, pInvoiceBlue.getAppKey(), iAppInterfaceForm.getInterfaceId());
                           logger.info(RetJsonObject);
                           logger.info(iAppInterfaceForm.getRequestUrl());
                           logger.info(result);

                       }
                   }
               }
           }
       }catch (Exception e){

           e.printStackTrace();
           logger.info(e);
       }



    }

    public List<IAppInterfaceForm> getRetUrl(String pAppKey, String pInterfaceId) {
        //============1,根据app_key和interface_id查询出i_app_interface表的guid====
        IAppInterfaceForm iAppInterfaceForm = iAppInterfaceService.getInfoByAppIfKey(pAppKey, pInterfaceId);
        //============3，根据guid，查询i_app_interface_asyn表所有需要回调的系统的returnUrl====
        logger.info("guid" + iAppInterfaceForm.getGuid());
        List<IAppInterfaceForm> iAppInterfaceFormList = iAppInterfaceService.getRetAppInterface(iAppInterfaceForm.getGuid());

        return iAppInterfaceFormList;
    }
}
